package com.tsing.websocket.controller;

import com.tsing.websocket.config.WebSocketServer;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Controller("web_Scoket_system")
@RequestMapping("/api/socket")
public class SystemController {
    //页面请求
    @GetMapping("/index/{userId}")
    public ModelAndView socket(@PathVariable String userId) {
        ModelAndView mav = new ModelAndView("/socket1");
        mav.addObject("userId", userId);
        return mav;
    }

    //推送数据接口
    @ResponseBody
    @GetMapping("/socket/push")
//    public Map pushToWeb(@PathVariable String cid, String message) {
    public Map pushToWeb( @RequestParam("cid") String cid) {
        Map<String,Object> result = new HashMap<>();
        String message = "Hello " + cid + "!";
        try {
            WebSocketServer.sendInfo(message, cid);
            result.put("code", cid);
            result.put("msg", message);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

    //推送数据接口
    @ResponseBody
    @GetMapping("/hello")
    public Map hello() {
        Map<String,Object> result = new HashMap<>();
        String message = "Hello " + 100 + "!";
        try {
            WebSocketServer.sendInfo(message, String.valueOf(100));
            result.put("code", 100);
            result.put("msg", message);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

}

